package com.glodon.paas.document.dao.mongo;

import java.util.List;

import com.glodon.paas.document.dao.RevisionDao;
import com.glodon.paas.document.dao.domain.RevisionEntity;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;

public class RevisionDaoMongoImpl extends MongoDBDao<RevisionEntity, String> implements RevisionDao {

    @Override
    public void ensureIndexes() {
        super.ensureIndexes();
        mongoDataStore.ensureIndex(this.entityClazz, "fileId");
    }

    @Override
    public List<RevisionEntity> getRevisionsByFile(String fileId) {
        Query<RevisionEntity> q = this.createQuery().filter("fileId", fileId).order("-revisionNumber");
        return q.asList();
    }

    @Override
    public RevisionEntity getLatestUnavailableRevision(String fileId) {
        Query<RevisionEntity> q = this.createQuery().filter("fileId", fileId).filter("partsCount >", 0).limit(1);
        return q.get();
    }

    @Override
    public RevisionEntity getLatestAvailableRevision(String fileId) {
        Query<RevisionEntity> q = this.createQuery().filter("fileId", fileId).filter("storageKey <>", "").order("-revisionNumber").limit(1);
        return q.get();
    }

    @Override
    public RevisionEntity getRevision(String fileId, int revisionNum) {
        Query<RevisionEntity> q = this.createQuery().filter("fileId", fileId).filter("revisionNumber", revisionNum);
        return q.get();
    }

    @Override
    public void updateRevision(RevisionEntity revision) {
        Query<RevisionEntity> q = this.createQuery().filter("id", revision.getId());
        super.update(q, revision);

    }

    @Override
    public void updateDataBagId(String revisionId, String dataBagId) {
        Query<RevisionEntity> q = this.createQuery().filter("id", revisionId);
        UpdateOperations<RevisionEntity> ops = this.createUpdateOperations().set("dataBagId", dataBagId);
        super.updateFirst(q, ops);

    }

    @Override
    public void deleteByFile(String fileId) {
        Query<RevisionEntity> q = this.createQuery().filter("fileId", fileId);
        super.deleteByQuery(q);
    }

    @Override
    public RevisionEntity getRevisionByDatabag(String databagId) {
        Query<RevisionEntity> q = this.createQuery().filter("dataBagId", databagId);
        return q.get();
    }

}
